<template>
  <div>
  <el-form ref="formRef" v-loading="formLoading" :model="formData" :rules="formRules" label-width="150px" :disabled="disabled">
    <el-row>
      <el-col :span="12">
        <el-form-item label="规则名称" prop="ruleName">
          <el-input v-model="formData.ruleName" clearable placeholder="请输入规则名称" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="应急响应级别">
          <el-row :gutter="5" style="width: 100%;">
            <el-col :span="7">
              <el-input v-model.number="formData.responseLevel1" onkeyup="value=value.replace(/[^\d]+/g,'')" 
                style="width:100%" clearable />
            </el-col>
            <el-col :span="4">
              <el-select v-model="formData.responseLevel2" clearable>
                <el-option v-for="item in symbolOption" :label="item.label" :value="item.value" />
              </el-select>
            </el-col>
            <el-col :span="2" style="text-align: center">
              级别
            </el-col>
            <el-col :span="4">
              <el-select v-model="formData.responseLevel3" clearable>
                <el-option v-for="item in symbol1Option" :label="item.label" :value="item.value" />
              </el-select>
            </el-col>
            <el-col :span="7" style="position: relative;">
              <el-input v-model.number="formData.responseLevel4" onkeyup="value=value.replace(/[^\d]+/g,'')"  style="width:100%" clearable />
            </el-col>
          </el-row>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="地震类型" prop="earthquakeType">
          <el-radio-group v-model="formData.earthquakeType">
            <el-radio value="1">正式</el-radio>
            <el-radio value="2">测试</el-radio>
            <el-radio value="3">演练</el-radio>
            <el-radio value="4">自动</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="震级范围">
          <el-row :gutter="5" style="width: 100%;">
            <el-col :span="7">
              <el-input-number v-model="formData.magnitude1" :precision="1" :step="1" controls-position="right"
                style="width:100%" clearable />
            </el-col>
            <el-col :span="4">
              <el-select v-model="formData.magnitude2" clearable>
                <el-option v-for="item in symbolOption" :label="item.label" :value="item.value" />
              </el-select>
            </el-col>
            <el-col :span="2" style="text-align: center">
              震级
            </el-col>
            <el-col :span="4">
              <el-select v-model="formData.magnitude3" clearable>
                <el-option v-for="item in symbol1Option" :label="item.label" :value="item.value" />
              </el-select>
            </el-col>
            <el-col :span="7" style="position: relative;">
              <el-input-number v-model="formData.magnitude4" :precision="1" :step="1" controls-position="right"
                style="width:100%" clearable />
            </el-col>
          </el-row>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="是否台湾区域" prop="isTw">
          <el-select v-model="formData.isTw" placeholder="请选择" clearable>
            <el-option v-for="item in isOption" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="接收用户组" prop="userGroups">
          <el-select v-model="formData.userGroups" multiple placeholder="请选择" clearable>
            <el-option v-for="item in groupList" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
  <div style="text-align: center;">
        <el-button :disabled="formLoading" type="primary" @click="submitForm" v-if="formType != '查看'">确 定</el-button>
        <el-button @click="setClose">取 消</el-button>
  </div>
</div>
</template>
<script lang="ts" setup>
import * as publishRuleApi from '@/api/infoArrive/teleMeeting/index'
import { getGroup } from '@/api/infoArrive/arriveNotice/userGroup'
import { getTemplateList } from '@/api/infoArrive/arriveNotice/messageTemplate/index'

defineOptions({ name: 'PublishRuleForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const disabled = ref(false)
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref<any>({
  ruleName: '',
  resLevelName: '',
  earthquakeType: '',//地震类型  1--正式地震  2--测试地震  3--演练地震  4--自动地震, 手动触发默认是2 测试地震
  isTw: '0',
  tempId: '',
  userGroups: [],
  magnitude1: undefined,
  magnitude2: 0,
  magnitude3: 0,
  magnitude4: undefined,
  responseLevel1: undefined,
  responseLevel2: 0,
  responseLevel3: 0,
  responseLevel4: undefined,
})
const symbol1Option = ref([
  { label: '≤', value: 0 }, { label: '<', value: 1 }, { label: '=', value: 2 },
])
const symbolOption = ref([
  { label: '≤', value: 0 }, { label: '<', value: 1 },
])
const isOption = ref([
  { label: '否', value: '0' }, { label: '是', value: '1' }
])

const formRules = reactive({
  ruleName: [{ required: true, message: '规则名称不能为空', trigger: 'blur' }],
  earthquakeType: [{ required: true, message: '地震类型不能为空', trigger: 'blur' }],
  tempId: [{ required: true, message: '请选择', trigger: 'change' }],
  userGroups: [{ required: true, message: '请选择', trigger: 'change' }],
  isTw: [{ required: true, message: '请选择', trigger: 'change' }],
  type: [{ required: true, message: '请选择', trigger: 'change' }],
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = type
  formType.value = type
  disabled.value = (type === '查看')
  resetForm()
  await getGroupList()
  await getTemplateLists()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await publishRuleApi.getPublishRule(id)
      formData.value.userGroups = formData.value.userGroups.split(',')
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success', 'setClose']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    if (formType.value === '新增') {
      await publishRuleApi.savePublishRule({ ...formData.value, userGroups: formData.value.userGroups.join(',') })
      message.success(t('common.createSuccess'))
    } else {
      await publishRuleApi.savePublishRule({ ...formData.value, userGroups: formData.value.userGroups.join(',') })
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
    setClose()
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    ruleName: '',
    resLevelName: '',
    earthquakeType: '',
    isTw: '0',
    tempId: '',
    userGroups: [],
    magnitude1: undefined,
    magnitude2: 0,
    magnitude3: 0,
    magnitude4: undefined,
    responseLevel1: undefined,
    responseLevel2: 0,
    responseLevel3: 0,
    responseLevel4: undefined,
  }
  formRef.value?.resetFields()
}

/** 获取信息模板的数据  */
const templateList = ref([] as any[])
const getTemplateLists = async () => {
  const { list } = await getTemplateList({ pageNo: 1, pageSize: 2000 })
  list.forEach(item => {
    item.label = item.templateName;
    item.value = item.id;
  })
  templateList.value = list
}
/** 获取用户组的数据  */
const groupList = ref([] as any[])
const getGroupList = async () => {
  const res = await getGroup({ groupType: '2' })
  res.list.forEach(item => {
    item.label = item.groupName;
    item.value = item.id;
  })
  groupList.value = res.list
}
const setClose = () => {
  dialogVisible.value = false
  emit('setClose')
}
</script>
